import { _decorator, Component, game, Node } from 'cc';
import EventManager from '../../Runtime/EventManager';
import { EVENT_ENUM, SHAKE_DIRECTION_ENUM } from '../../Enums';
const { ccclass, property } = _decorator;

@ccclass('ShakeManager')
export class ShakeManager extends Component {
    private isShaking: boolean = false
    private oldTime: number = 0
    private oldPos: { x: number, y: number } = { x: 0, y: 0 }
    private type: SHAKE_DIRECTION_ENUM

    onLoad() {
        EventManager.Instance.on(EVENT_ENUM.SCREEN_SHAKE, this.onShake, this)
    }

    /**屏幕震动 */
    onShake(type: SHAKE_DIRECTION_ENUM) {
        if (this.isShaking) {
            return
        }
        this.type = type
        this.oldTime = game.totalTime
        this.isShaking = true
        this.oldPos.x = this.node.position.x
        this.oldPos.y = this.node.position.y
    }

    stopShake() {
        this.isShaking = false
    }

    update(deltaTime: number) {
        if (this.isShaking) {
            const amount = 10
            const frequency = 12
            const currentTime = (game.totalTime - this.oldTime) / 1000

            const offset = amount * Math.sin((frequency * Math.PI) * currentTime)//震动偏移量
            if (this.type === SHAKE_DIRECTION_ENUM.TOP) {
                this.node.setPosition(this.oldPos.x, this.oldPos.y + offset)
            } else if (this.type === SHAKE_DIRECTION_ENUM.BOTTOM) {
                this.node.setPosition(this.oldPos.x, this.oldPos.y - offset)
            } else if (this.type === SHAKE_DIRECTION_ENUM.LEFT) {
                this.node.setPosition(this.oldPos.x - offset, this.oldPos.y)
            } else if (this.type === SHAKE_DIRECTION_ENUM.RIGHT) {
                this.node.setPosition(this.oldPos.x + offset, this.oldPos.y)
            }

            if (currentTime > 0.2) {
                this.isShaking = false
                this.node.setPosition(this.oldPos.x, this.oldPos.y)
            }

        }
    }

    onDestroy() {
        EventManager.Instance.off(EVENT_ENUM.SCREEN_SHAKE, this.onShake)
    }
}


